<template>
	<view v-if="isShow" class="x-image-edit" :style="{ width: sysInfo.windowWidth+'px' }">
		<image src="../../static/close.png"
			style="width: 30px;height: 30px;position: absolute;top: 10px;right: 10px;z-index: 9;" @click="close()">
		</image>
		<view class="work-panel">
			<!-- 容器 -->
			<view v-if="imgUrl" class="image-edit-container"
				:style="{ height: imgScaleH+'px', width: imgScaleW+'px', transform: 'rotate('+rotate+'deg)' }">
				<!-- 图片 -->
				<view class="image-edit-container-panel">
					<image :src="imgUrl" mode="aspectFit"></image>
				</view>
				<!-- 画板 -->
				<view v-if="currentType === TOOL_TYPE.LINE || currentType === TOOL_TYPE.DIAGRAM"
					class="image-edit-container-canvas"
					:style="{ height: imgScaleH+'px', width: imgScaleW+'px', zIndex: 10 }">
					<canvas :style="{ height: imgScaleH+'px', width: imgScaleW+'px' }" :canvas-id="CANVAS_ID"
						@touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
					</canvas>
				</view>
				<view v-if="currentType === TOOL_TYPE.DIAGRAM" class="image-edit-container-canvas diagram"
					:style="{ height: imgScaleH+'px', width: imgScaleW+'px' }">
					<canvas :style="{ height: imgScaleH+'px', width: imgScaleW+'px' }" canvas-id="DIAGRAM" type="2d">
					</canvas>
				</view>
				<!-- 蒙版 -->
				<view v-if="currentType === TOOL_TYPE.ROTATE || currentType === TOOL_TYPE.TEXT"
					class="image-edit-container-mask" :style="{ height: imgScaleH+'px', width: imgScaleW+'px' }"
					@click.stop="maskClick">
					<template v-if="currentType === TOOL_TYPE.TEXT">
						<view v-for="(textarea, index) in textContainers">
							<view ref="textView" id="x-image-edit-text-view"
								:class="['text-view', { 'active-text': currentTextArea === index }]"
								@click.stop="setCurrentTextArea(index)" @touchstart.stop="textTouchStart($event, index)"
								@touchmove.stop="textTouchMove($event, index)" :key="index" :style="{
								  width: TEXTAREA_W+'px',
								  minHeight: TEXTAREA_H+'px' ,
								  top: textarea.location.top+'px',
								  left: textarea.location.left+'px',
								  right: textarea.location.right+'px',
								  bottom: textarea.location.bottom+'px'
								}">
								<view @click="deleteTextArea(index)" class="delete-text"
									v-if="currentTextArea === index">
									<u-icon name="close" color="#2979ff" size="13"></u-icon>
								</view>
								<textarea :focus="currentTextArea === index"
									:placeholderStyle="'color: ' + textarea.color"
									:style="{ backgroundColor: 'transparent', width: '100%', color: textarea.color }"
									v-model="textarea.text" placeholder="请输入内容" autoHeight>
								</textarea>
							</view>
						</view>
					</template>
				</view>
				<!-- 剪切蒙版 -->
				<view v-if="currentType === TOOL_TYPE.CROP" class="image-edit-container-crop" :style="{
						top: cropContainer.top+'px',
						bottom: cropContainer.bottom+'px',
						left: cropContainer.left+'px',
						right: cropContainer.right+'px'
					}">
					<view @touchmove.stop="cropTouchMove($event, CROP_TYPE.TOP_LEFT)" @touchstart.stop="cropTouchStart"
						class="top-left"></view>
					<view @touchmove.stop="cropTouchMove($event, CROP_TYPE.TOP_RIGHT)" @touchstart.stop="cropTouchStart"
						class="top-right"></view>

					<view @touchmove.stop="cropTouchMove($event, CROP_TYPE.BOTTOM_RIGHT)"
						@touchstart.stop="cropTouchStart" class="bottom-right"></view>
					<view @touchmove.stop="cropTouchMove($event, CROP_TYPE.BOTTOM_LEFT)"
						@touchstart.stop="cropTouchStart" class="bottom-left"></view>
				</view>
			</view>
		</view>
		<view
			v-if="[TOOL_TYPE.CROP, TOOL_TYPE.LINE, TOOL_TYPE.TEXT, TOOL_TYPE.ROTATE, TOOL_TYPE.DIAGRAM].includes(currentType)"
			:class="['action', 'default-action-height', { 'ios': iOS_SYS }]">
			<template v-if="currentType === TOOL_TYPE.CROP">
				<text @click="cropCancel" class="text-size">取消</text>
				<text @click="cropSave" class="text-size">确认</text>
			</template>
			<template v-if="currentType === TOOL_TYPE.LINE">
				<view class="font-size">
					<view v-for="size in LINE_SIZE" :key="size"
						:class="['circle-border', 'font-size-item', { 'active-border': lineAction.size === size }]"
						:style="{ width: size+'px', height: size+'px', backgroundColor: lineAction.color }"
						@click="setLineSize(size)">

					</view>
				</view>
				<view @click="lineCancel" class="text-size">取消</view>
				<view v-for="color in COLOR"
					:class="['circle-border', 'color', {'active-border': lineAction.color === color}]"
					:style="{ backgroundColor: color }" :key="color" @click="setLineColor(color)">
				</view>
				<view @click="saveLine(null)" class="text-size">确认</view>
			</template>
			<template v-if="currentType === TOOL_TYPE.TEXT">
				<view @click="TextCancel" class="text-size">取消</view>
				<view v-for="color in COLOR"
					:class="['circle-border', 'color', {'active-border': currentTextColor === color}]"
					:style="{ backgroundColor: color }" :key="color" @click="setTextColor(color)">
				</view>
				<view class="text-size" @click="saveText">确认</view>
			</template>
			<template v-if="currentType === TOOL_TYPE.ROTATE">
				<view class="text-size" @click="rotateCancel">取消</view>
				<image @click="rotateType('left')" style="width: 50rpx;height: 50rpx;" class="img-icon"
					src="@/static/image-edit/rotate-left.png"></image>
				<image @click="rotateType('right')" style="width: 50rpx;height: 50rpx;" class="img-icon"
					src="@/static/image-edit/rotate-right.png"></image>
				<view class="text-size" @click="rotateSave">确认</view>
			</template>
			<template v-if="currentType === TOOL_TYPE.DIAGRAM">
				<view @click="diagramCancel" class="text-size">取消</view>
				<view @click="diagramBack" class="text-size">撤销</view>
				<image v-if="diragamAction.type === DIAGRAM_TYPE.ARROW" style="width: 50rpx;height: 50rpx;"
					class="img-icon" src="../../static/image-edit/arrow-active.png" mode=""></image>
				<image @click="setDiagramType(DIAGRAM_TYPE.ARROW)" v-else style="width: 50rpx;height: 50rpx;"
					class="img-icon" src="../../static/image-edit/arrow.png" mode=""></image>

				<image v-if="diragamAction.type === DIAGRAM_TYPE.CIRCLE" style="width: 50rpx;height: 50rpx;"
					class="img-icon" src="../../static/image-edit/circle-active.png" mode=""></image>
				<image @click="setDiagramType(DIAGRAM_TYPE.CIRCLE)" v-else style="width: 50rpx;height: 50rpx;"
					class="img-icon" src="../../static/image-edit/circle.png" mode=""></image>

				<image v-if="diragamAction.type === DIAGRAM_TYPE.RECTANGLE" style="width: 50rpx;height: 50rpx;"
					class="img-icon" src="../../static/image-edit/rectangle-active.png" mode=""></image>
				<image @click="setDiagramType(DIAGRAM_TYPE.RECTANGLE)" v-else style="width: 50rpx;height: 50rpx;"
					class="img-icon" src="../../static/image-edit/rectangle.png" mode=""></image>
				<view @click="saveDiagram" class="text-size">确认</view>
			</template>
		</view>
		<view :class="['control-tool', { 'ios': iOS_SYS }]"
			v-if="!([TOOL_TYPE.CROP, TOOL_TYPE.LINE, TOOL_TYPE.TEXT, TOOL_TYPE.ROTATE, TOOL_TYPE.DIAGRAM].includes(currentType))">
<!-- 			<view @click="controlSelect(TOOL_TYPE.CROP)" class="control-item crop">
				<view v-show="!(currentType === TOOL_TYPE.CROP)">
					<image class="img-icon" src="@/static/image-edit/crop.png"></image>
				</view>
				<view v-show="currentType === TOOL_TYPE.CROP">
					<image class="img-icon" src="@/static/image-edit/crop-active.png"></image>
				</view>
			</view> -->
<!-- 			<view @click="controlSelect(TOOL_TYPE.TEXT)" class="control-item text">
				<view v-show="!(currentType === TOOL_TYPE.TEXT)">
					<image class="img-icon" src="@/static/image-edit/text.png"></image>
				</view>
				<view v-show="currentType === TOOL_TYPE.TEXT">
					<image class="img-icon" src="@/static/image-edit/text-active.png"></image>
				</view>
			</view> -->
			<view @click="controlSelect(TOOL_TYPE.LINE)" class="control-item line">
				<view v-if="!(currentType === TOOL_TYPE.LINE)">
					<image class="img-icon" src="@/static/image-edit/pen.png"></image>
				</view>
				<view v-if="currentType === TOOL_TYPE.LINE">
					<image class="img-icon" src="@/static/image-edit/pen-active.png"></image>
				</view>
			</view>
<!-- 			<view @click="controlSelect(TOOL_TYPE.DIAGRAM)" class="control-item line">
				<image class="img-icon" src="@/static/image-edit/arrow.png"></image>
			</view> -->
<!-- 			<view @click="controlSelect(TOOL_TYPE.ROTATE)" class="control-item rotate">
				<view v-show="!(currentType === TOOL_TYPE.ROTATE)">
					<image class="img-icon" src="@/static/image-edit/retweet.png"></image>
				</view>
				<view v-show="currentType === TOOL_TYPE.ROTATE">
					<image class="img-icon" src="@/static/image-edit/retweet-active.png"></image>
				</view>
			</view> -->
			<view @click="reset" class="text-size control-item save">还原</view>
			<view @click="handleOK" class="text-size control-item save">发送</view>
		</view>
		<view v-if="saveCanvasLoading" style="opacity: 0;position: absolute;">
			<canvas :style="{ height: saveCanvas.height+'px', width: saveCanvas.width+'px' }"
				canvas-id="image-save"></canvas>
		</view>
		<view style="opacity: 0;position: absolute;left: 2000rpx;">
			<canvas id="x-image-edit-text-canvas" canvas-id="text-canvas"></canvas>
		</view>
	</view>
</template>

<script>
	import {
		getImgScale,
		TOOL_TYPE,
		CROP_TYPE,
		COLOR,
		TextArea,
		drawText,
		LINE_SIZE,
		getTextAreaHeight,
		DIAGRAM_TYPE,
		arrowPoint,
		drawArrow
	} from './utils.js'
	import EVENT_CONSTANTS from '@/config/constants/EVENT_CONSTANTS.js'

	const sysInfo = uni.getSystemInfoSync();
	const MAX_H = sysInfo.windowHeight * 0.6 // 图片编辑容器最大高度 屏幕高 * 60%
	const MAX_W = sysInfo.windowWidth * 0.9 // 图片编辑容器最大宽度 屏幕宽 * 80%
	const CROP_MIN_H = 50 // 剪切区域最小高度 50px
	const CROP_MIN_W = 50 // 剪切区域最小宽度 50px
	const SCREEN_RATIO = MAX_W / MAX_H // 图片编辑容器宽高比
	const CONTROL_TOOL_H = 100 // 菜单栏 100px
	const CANVAS_ID = 'image-edit-id'
	const SAVE_CANVAS_ID = 'image-save'
	const FONT_SIZE = 16 // 字体大小 17px
	const LINE_W = 4 // 笔画粗细 4px
	const TEXTAREA_W = 100 // 文本域宽 100px
	const TEXTAREA_H = 20 // 文本域高 40px 
	const TEXTAREA_PADDING = 10 // 文本域padding
	const TEXTAREA_BORDER = 2 // 文本域padding
	const DEFAULT_TEXT_COLOR = '#FA3534' // 文本默认颜色
	const DEFAULT_ARROW_OPTION = {
		theta: 30,
		headlen: 20,
		width: 4,
		color: '#FA3534'
	}
	const DEFAULT_DIAGRAM_COLOR = '#FA3534' // 矩形默认颜色
	const DEFAULT_DIAGRAM_SIZE = 4 // 矩形默认大小
	const FONT_HEIGHT = 21 // text文本域单行字体高度
	const iOS_SYS = sysInfo.osName === 'ios'

	let IMG_RATIO = 1 //图片比例
	let ORG_IMG = '' // 图片源地址

	export default {
		data() {
			return {
				DIAGRAM_TYPE,
				CROP_TYPE,
				TOOL_TYPE,
				CANVAS_ID,
				COLOR,
				CONTROL_TOOL_H,
				TEXTAREA_W,
				TEXTAREA_H,
				LINE_SIZE,
				iOS_SYS,
				// 系统参数
				sysInfo: sysInfo,
				isShow: false,
				saveCanvas: { // 保存图层的画板信息
					width: 0,
					height: 0
				},
				cropContainer: { // 剪切框容器
					top: 0,
					left: 0,
					right: 0,
					bottom: 0
				},
				textContainers: [], // 文本的文本域集合
				// 图片参数
				imageInfo: { // 图片信息
					width: 0,
					height: 0
				},
				imgUrl: '', // 图片路径
				scale: 1, // 缩放比
				rotate: 0,
				// 操作参数
				currentType: null, // 当前操作功能
				currentTextArea: -1, // 当前选中文本框
				lineAction: { // 线条配置
					color: '#000',
					size: FONT_SIZE
				},
				diragamAction: {
					startPoint: {
						x: 0,
						y: 0
					},
					type: DIAGRAM_TYPE.ARROW,
					saves: []
				},
				cropAction: { // 剪切配置
					startPoint: {
						x: 0,
						y: 0
					},
					startMove: false
				},
				textAction: { // 文本配置
					startPoint: {
						x: 0,
						y: 0
					},
					startMove: false,
					moveIndex: -1
				},
				ctx: null,
				saveing: false, // 保存中
				saveCanvasLoading: false,
				currentTextColor: DEFAULT_TEXT_COLOR,
				offsetLeft: '',
				offsetTop: ''
			}
		},
		mounted() {},
		computed: {
			imgScaleW() {
				return this.imageInfo.width * this.scale
			},
			imgScaleH() {
				return this.imageInfo.height * this.scale
			},
		},
		methods: {
			/**
			 * 初始化画板
			 */
			initCanvas() {
				// 字体大小
				this.ctx.setFontSize(FONT_SIZE)
				// 线条粗细
				// #ifndef MP
				this.ctx.lineWidth = LINE_W
				// #endif
				// #ifdef MP
				this.ctx.setLineWidth(LINE_W)
				// #endif
			},
			/**
			 * 剪切框拖动开始
			 * @param {Object} e 事件参数
			 */
			cropTouchStart(e) {
				this.cropAction.startPoint.x = e.touches[0].pageX
				this.cropAction.startPoint.y = e.touches[0].pageY
				this.cropAction.startMove = true
			},
			/**
			 * 剪切框拖动结束
			 * @param {Object} e 拖动时事件参数
			 * @param {String} type 拖动剪切框位置
			 */
			cropTouchMove(e, type) {
				const {
					pageX,
					pageY
				} = e.touches[0]
				const moveXLen = pageX - this.cropAction.startPoint.x
				const moveYLen = pageY - this.cropAction.startPoint.y
				const L = this.cropContainer.left + moveXLen
				const T = this.cropContainer.top + moveYLen
				const R = this.cropContainer.right - moveXLen
				const B = this.cropContainer.bottom - moveYLen

				if (type === CROP_TYPE.TOP) {

				} else if (type === CROP_TYPE.TOP_LEFT) {
					console.log(L >= 0 && L <= this.imgScaleW && this.imgScaleW - (this.cropContainer.right + L) >=
						CROP_MIN_W);
					if (L >= 0 && L <= this.imgScaleW && this.imgScaleW - (this.cropContainer.right + L) >= CROP_MIN_W) {
						this.cropContainer.left = L
					}
					if (T >= 0 && T <= this.imgScaleH && this.imgScaleH - (this.cropContainer.bottom + T) >= CROP_MIN_H) {
						this.cropContainer.top = T
					}
				} else if (type === CROP_TYPE.TOP_RIGHT) {
					if (T >= 0 && T <= this.imgScaleH && this.imgScaleH - (this.cropContainer.bottom + T) >= CROP_MIN_H) {
						this.cropContainer.top = T
					}
					if (R >= 0 && R <= this.imgScaleW && this.imgScaleW - (this.cropContainer.left + R) >= CROP_MIN_W) {
						this.cropContainer.right = R
					}
				} else if (type === CROP_TYPE.BOTTOM) {

				} else if (type === CROP_TYPE.BOTTOM_LEFT) {
					if (L >= 0 && L <= this.imgScaleW && this.imgScaleW - (this.cropContainer.right + L) >= CROP_MIN_W) {
						this.cropContainer.left = L
					}
					if (B >= 0 && B <= this.imgScaleH && this.imgScaleH - (this.cropContainer.top + B) >= CROP_MIN_H) {
						this.cropContainer.bottom = B
					}
				} else if (type === CROP_TYPE.BOTTOM_RIGHT) {
					if (R >= 0 && R <= this.imgScaleW && this.imgScaleW - (this.cropContainer.left + R) >= CROP_MIN_W) {
						this.cropContainer.right = R
					}
					if (B >= 0 && B <= this.imgScaleH && this.imgScaleH - (this.cropContainer.top + B) >= CROP_MIN_H) {
						this.cropContainer.bottom = B
					}
				} else if (type === CROP_TYPE.LEFT) {

				} else if (type === CROP_TYPE.RIGHT) {

				}
				this.cropAction.startPoint.x = e.touches[0].pageX
				this.cropAction.startPoint.y = e.touches[0].pageY
			},
			/**
			 * 保存剪切图片
			 */
			cropSave() {
				this.getImage('', () => {
					this.cropCancel()
				})
			},
			/**
			 * 取消剪切图片
			 */
			cropCancel() {
				this.cropContainer = {
					top: 0,
					left: 0,
					right: 0,
					bottom: 0
				}
				this.currentType = null
			},
			/**
			 * 文本取消
			 */
			TextCancel() {
				this.textContainers = []
				this.currentType = null
			},
			/**
			 * 设置当前选择的text框
			 * @param {Number} index 索引
			 */
			setCurrentTextArea(index) {
				this.currentTextArea = index
			},
			addTextArea(color = '') {
				const textArea = new TextArea(TEXTAREA_W, TEXTAREA_H, this.imgScaleW, this.imgScaleH)
				textArea.color = color ? color : DEFAULT_TEXT_COLOR
				this.textContainers.push(textArea)
				this.currentTextArea = this.textContainers.length - 1
			},
			/**
			 * 设置字体颜色
			 * @param {String} color 颜色
			 */
			setTextColor(color) {
				this.currentTextColor = color
				if (this.currentTextArea > -1 && this.textContainers[this.currentTextArea]) {
					this.textContainers[this.currentTextArea].color = color
				}
			},
			/**
			 * 文本域拖动开始
			 * @param {Object} e 拖动事件
			 * @param {Number} index 拖动索引
			 */
			textTouchStart(e, index) {
				const {
					pageX,
					pageY
				} = e.touches[0]
				this.textAction.startPoint = {
					x: pageX,
					y: pageY
				}
				this.textAction.moveIndex = index
				this.textAction.startMove = true
			},
			deleteTextArea(index) {
				this.textContainers.splice(index, 1)
			},
			saveText() {
				this.saveCanvas.height = this.imgScaleH
				this.saveCanvas.width = this.imgScaleW
				this.saveCanvasLoading = true
				const _this = this
				this.$nextTick(() => {
					const ctx = uni.createCanvasContext(SAVE_CANVAS_ID, this)
					ctx.drawImage(_this.imgUrl, 0, 0, _this.imgScaleW, _this.imgScaleH);
					ctx.draw()

					_this.textContainers.forEach(item => {
						drawText(
							this,
							SAVE_CANVAS_ID,
							item,
							FONT_SIZE,
							FONT_HEIGHT,
							TEXTAREA_W,
							item.location.left + 10,
							item.location.top + 10 + FONT_HEIGHT
						)
					})
					uni.showLoading()
					setTimeout(() => {
						uni.canvasToTempFilePath({
							x: 0,
							y: 0,
							width: _this.imgScaleW,
							height: _this.imgScaleH,
							destWidth: _this.imgScaleW / _this.scale,
							destHeight: _this.imgScaleH / _this.scale,
							quality: 1,
							canvasId: SAVE_CANVAS_ID,
							success: function(res) {
								_this.imgUrl = res.tempFilePath
								_this.saveCanvasLoading = false
								_this.TextCancel()
								uni.hideLoading()
							},
							fail: function(err) {
								_this.toast.default('保存失败')
							}
						});
					}, 200)
				})
			},
			/**
			 * 文本域拖动中
			 * @param {Object} e 拖动事件
			 */
			textTouchMove(e) {
				const {
					pageX,
					pageY
				} = e.touches[0]
				const textArea = this.textContainers[this.textAction.moveIndex]
				if (textArea) {
					const textViewNode = this.$refs.textView.$el ? this.$refs.textView.$el : this.$refs.textView[this
						.textAction.moveIndex].$el
					// 文本域宽高
					const _H = textViewNode.clientHeight + TEXTAREA_PADDING * 2
					const _W = TEXTAREA_W + TEXTAREA_PADDING * 2 + TEXTAREA_BORDER * 2
					// 移动距离
					const moveXLen = pageX - this.textAction.startPoint.x
					const moveYLen = pageY - this.textAction.startPoint.y
					// 坐标
					const L = textArea.location.left + moveXLen
					const T = textArea.location.top + moveYLen
					if ((L >= 0 && L <= (this.imgScaleW - _W)) && (T >= 0 && T <= (this.imgScaleH - _H))) {
						this.textContainers[this.textAction.moveIndex].location.top = T
						this.textContainers[this.textAction.moveIndex].location.left = L
					}
					this.textAction.startPoint = {
						x: pageX,
						y: pageY
					}
				}

			},
			/**
			 * 遮罩层点击
			 */
			maskClick() {
				if (this.currentType === TOOL_TYPE.TEXT) {
					if (this.currentTextArea > -1) {
						if (this.textContainers[this.currentTextArea] && !this.textContainers[this.currentTextArea].text) {
							this.textContainers.splice(this.currentTextArea, 1)
						}
						this.currentTextArea = -1
					} else {
						this.addTextArea(this.currentTextColor)
					}
				}
			},
			/**
			 * 画板划线拖动开始位置
			 * @param {Object} e 事件参数
			 */
			touchStart(e) {
				if (this.currentType === TOOL_TYPE.LINE) {
					this.ctx = uni.createCanvasContext(this.CANVAS_ID, this)
					this.initCanvas()
					// #ifndef MP
					this.ctx.lineWidth = this.lineAction.size ? this.lineAction.size : LINE_W
					this.ctx.strokeStyle = this.lineAction.color
					this.ctx.lineJoin = 'round'
					this.ctx.lineCap = 'round'
					// #endif
					// #ifdef MP
					this.ctx.setLineWidth(this.lineAction.size ? this.lineAction.size : LINE_W)
					this.ctx.setStrokeStyle(this.lineAction.color)
					this.ctx.setLineJoin('round')
					this.ctx.setLineCap('round')
					// #endif


					// #ifndef MP
					const {
						x,
						y
					} = e.changedTouches[0]
					// #endif
					// #ifdef MP
					const x = e.changedTouches[0].clientX - this.offsetLeft
					const y = e.changedTouches[0].clientY - this.offsetTop
					// #endif
					this.lineAction.startPoint = {
						x,
						y
					}
					// 起点与移动的连接断开
					this.lineAction.moveX = ''
					this.lineAction.moveY = ''
				} else if (this.currentType === TOOL_TYPE.DIAGRAM) {
					this.ctx = uni.createCanvasContext(this.CANVAS_ID, this)
					this.initCanvas()
					this.ctx.lineWidth = DEFAULT_DIAGRAM_SIZE
					this.ctx.strokeStyle = DEFAULT_DIAGRAM_COLOR
					this.ctx.lineJoin = 'round'

					const {
						x,
						y
					} = e.changedTouches[0]
					this.diragamAction.startPoint = {
						x,
						y
					}

					console.log(1);
				}
			},
			/**
			 * 画板划线拖动时位置
			 * @param {Object} e 事件参数
			 */
			touchMove(e) {
				if (this.currentType === TOOL_TYPE.LINE) {
					// #ifndef MP
					const {
						x,
						y
					} = e.changedTouches[0]
					this.ctx.strokeStyle = this.lineAction.color
					// #endif
					// #ifdef MP
					const x = e.changedTouches[0].clientX - this.offsetLeft
					const y = e.changedTouches[0].clientY - this.offsetTop
					this.ctx.setStrokeStyle(this.lineAction.color)
					// #endif

					if (this.lineAction.moveX && this.lineAction.moveY) {
						this.ctx.moveTo(this.lineAction.moveX, this.lineAction.moveY)
						this.ctx.lineTo(this.lineAction.moveX, this.lineAction.moveY)
					}
					this.ctx.lineTo(x, y)
					this.lineAction.moveX = x
					this.lineAction.moveY = y
					this.ctx.stroke()
					// ture，保留之前的内容
					this.ctx.draw(true)
				} else if (this.currentType === TOOL_TYPE.DIAGRAM) {
					const {
						x,
						y
					} = e.changedTouches[0]
					this.diagramDraw(this.ctx, this.diragamAction.startPoint, {
						x,
						y
					}, DEFAULT_ARROW_OPTION, this.diragamAction.type, false)
				}
			},
			touchEnd(e) {
				if (this.currentType === TOOL_TYPE.DIAGRAM) {
					const dctx = uni.createCanvasContext('DIAGRAM', this)
					const {
						x,
						y
					} = e.changedTouches[0]

					this.diragamAction.saves.push({
						start: {
							x: this.diragamAction.startPoint.x,
							y: this.diragamAction.startPoint.y
						},
						end: {
							x,
							y
						},
						option: {
							theta: DEFAULT_ARROW_OPTION.theta,
							headlen: DEFAULT_ARROW_OPTION.headlen,
							width: DEFAULT_ARROW_OPTION.width,
							color: DEFAULT_ARROW_OPTION.color
						},
						type: this.diragamAction.type
					})

					this.diagramDraw(dctx, this.diragamAction.startPoint, {
						x,
						y
					}, DEFAULT_ARROW_OPTION, this.diragamAction.type, true)

					this.ctx.clearRect(0, 0, this.imgScaleW, this.imgScaleH)
					this.ctx.draw()
				}
			},
			/**
			 * 绘制图形
			 * @param {Object} ctx 画布
			 * @param {Object} start 开始坐标
			 * @param {Object} end 结束坐标
			 * @param {Object} arrowOption 箭头配置
			 * @param {Object} type 图形类型
			 * @param {Object} save 是否保存
			 */
			diagramDraw(ctx, start, end, arrowOption, type, save) {
				if (type === DIAGRAM_TYPE.ARROW) {
					drawArrow(
						ctx,
						start.x,
						start.y,
						end.x,
						end.y,
						arrowOption.theta,
						arrowOption.headlen,
						arrowOption.width,
						arrowOption.color,
						save
					)
				} else if (type === DIAGRAM_TYPE.CIRCLE) {
					ctx.lineWidth = DEFAULT_DIAGRAM_SIZE
					ctx.strokeStyle = DEFAULT_DIAGRAM_COLOR
					ctx.lineJoin = 'round'
					const diffx = end.x - start.x
					const diffy = end.y - start.y
					const r = Math.sqrt(diffx * diffx + diffy * diffy)
					ctx.beginPath();
					ctx.arc(end.x - diffx / 2, end.y - diffy / 2, r / 2, 0, 2 * Math.PI);
					ctx.stroke();
					ctx.draw(save)
				} else if (type === DIAGRAM_TYPE.RECTANGLE) {
					ctx.lineWidth = DEFAULT_DIAGRAM_SIZE
					ctx.strokeStyle = DEFAULT_DIAGRAM_COLOR
					ctx.lineJoin = 'round'
					ctx.rect(start.x, start.y, end.x - start.x, end.y - start.y);
					ctx.stroke();
					ctx.draw(save)
				}
			},
			/**
			 * 取消图形绘制
			 */
			diagramCancel() {
				const dctx = uni.createCanvasContext('DIAGRAM', this)
				if (!dctx) {
					this.currentType = null
					return
				}
				dctx.clearRect(0, 0, this.imgScaleW, this.imgScaleH)
				dctx.draw()
				this.currentType = null
			},
			/**
			 * 撤销图形绘制
			 */
			diagramBack() {
				if (this.diragamAction.saves.length <= 0) {
					return
				}
				// 清除
				const dctx = uni.createCanvasContext('DIAGRAM', this)
				dctx.clearRect(0, 0, this.imgScaleW, this.imgScaleH)
				dctx.draw()
				// 重新绘制
				this.diragamAction.saves.splice(this.diragamAction.saves.length - 1, 1)
				this.diragamAction.saves.forEach(item => {
					this.diagramDraw(dctx, item.start, item.end, DEFAULT_ARROW_OPTION, item.type, true)
				})
			},
			/**
			 * 设置图形类型
			 * @param {Object} type
			 */
			setDiagramType(type) {
				this.diragamAction.type = type
			},
			/**
			 * 保存图形
			 */
			saveDiagram() {
				const _this = this
				this.saveing = true
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: _this.imgScaleW,
					height: _this.imgScaleH,
					destWidth: _this.imgScaleW / _this.scale,
					destHeight: _this.imgScaleH / _this.scale,
					quality: 1,
					canvasId: 'DIAGRAM',
					success: function(res) {
						_this.getImage(res.tempFilePath, () => {
							_this.currentType = null
						})
					},
					fail: function(err) {
						console.log(err);
					}
				});
			},
			/**
			 * 设置线条颜色
			 * @param {String} color 线条字体颜色
			 */
			setLineColor(color) {
				this.lineAction.color = color
			},
			setLineSize(lineSize) {
				this.lineAction.size = lineSize
			},
			/**
			 * 取消划线
			 */
			lineCancel() {
				if (!this.ctx) {
					this.currentType = null
					return
				}
				this.ctx.clearRect(0, 0, this.imgScaleW, this.imgScaleH)
				this.ctx.draw()
				this.currentType = null
			},
			/**
			 * 保存划线
			 */
			saveLine(type = '') {
				const _this = this
				this.saveing = true
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: _this.imgScaleW,
					height: _this.imgScaleH,
					destWidth: _this.imgScaleW / _this.scale,
					destHeight: _this.imgScaleH / _this.scale,
					quality: 1,
					canvasId: _this.CANVAS_ID,
					success: function(res) {
						console.log(res.tempFilePath)
						_this.getImage(res.tempFilePath, () => {
							_this.currentType = type
						})
					},
					fail: function(err) {
						console.log(err)
					}
				}, this);
			},
			/**
			 * 旋转保存
			 */
			rotateSave() {
				if (this.rotate === 0) {
					this.rotateCancel()
					return
				}
				this.getImage(null, () => {
					this.rotateCancel()
				})
			},
			/**
			 * 旋转取消
			 */
			rotateCancel() {
				this.rotate = 0
				this.currentType = -1
			},
			/**
			 * 旋转图片
			 * @param {Object} type 旋转类型
			 */
			rotateType(type) {
				if (type === 'left') {
					this.rotate = this.rotate === 0 ? 270 : this.rotate - 90
				} else {
					this.rotate = (this.rotate + 90) % 360
				}
			},
			/**
			 * 打开图片编辑框
			 */
			open(url, init = true) {
				uni.getSystemInfo({
					success: function (res) {
						this.sysInfo = res
						// console.log(res)
					}
				});
				const _this = this
				if (init) {
					ORG_IMG = url
					uni.$emit(EVENT_CONSTANTS.GLOBAL_HIDE_TABBAR, false)
				}
				uni.getImageInfo({
					src: url,
					success(res) {
						IMG_RATIO = res.width / res.height
						_this.imageInfo = res
						_this.scale = getImgScale(res.width, res.height, MAX_W, MAX_H)
						_this.imgUrl = res.path
						_this.isShow = true
						// #ifdef MP
						_this.$nextTick(() => {
							wx.createSelectorQuery().in(_this).select('.image-edit-container')
								.boundingClientRect(function(rect) {
									// console.log(rect, '00')
									_this.offsetLeft = rect.left
									_this.offsetTop = rect.top
								}).exec();
						})
						// #endif
					},
					fail(err) {
						_this.toast.default('打开图片失败')
					}
				})
			},
			/**
			 * 关闭
			 */
			close() {
				this.$emit('close')
				this.isShow = false
			},
			reset() {
				this.open(ORG_IMG, false)
			},
			/**
			 * 菜单栏选择
			 * @param {String} type 菜单ID
			 */
			controlSelect(type) {
				if (type === this.TOOL_TYPE.TEXT) {
					this.currentTextColor = DEFAULT_TEXT_COLOR
					this.currentType = type
					this.addTextArea()
				} else if (type === TOOL_TYPE.ROTATE) {
					this.currentType = type
				} else if (type === TOOL_TYPE.DIAGRAM) {
					this.diragamAction.startPoint = {
						x: 0,
						y: 0
					}
					this.diragamAction.saves = []
					this.diragamAction.type = DIAGRAM_TYPE.ARROW
					this.currentType = type
				} else {
					this.currentType = type
				}
			},
			/**
			 * 获取图片
			 * @param {String} canvasImgUrl 画板绘制的图片url
			 * @param {Function} callback 回调
			 */
			getImage(canvasImgUrl = '', callback = () => {}) {
				const loadMsg = '保存中...'
				const saveCanvasId = SAVE_CANVAS_ID
				const _this = this

				if (this.currentType === TOOL_TYPE.LINE || this.currentType === TOOL_TYPE.DIAGRAM) {
					this.saveCanvas.width = _this.imgScaleW
					this.saveCanvas.height = _this.imgScaleH
					this.saveCanvasLoading = true

					this.$nextTick(() => {
						const ctx = uni.createCanvasContext(saveCanvasId, this)
						uni.showLoading({
							title: loadMsg,
						});

						ctx.drawImage(_this.imgUrl, 0, 0, _this.imgScaleW, _this.imgScaleH);
						ctx.draw(true)

						ctx.drawImage(canvasImgUrl, 0, 0, _this.imgScaleW, _this.imgScaleH)
						ctx.draw(true)

						setTimeout(() => {
							uni.canvasToTempFilePath({
								x: 0,
								y: 0,
								width: _this.imgScaleW,
								height: _this.imgScaleH,
								destWidth: _this.imgScaleW / _this.scale,
								destHeight: _this.imgScaleH / _this.scale,
								quality: 1,
								canvasId: SAVE_CANVAS_ID,
								success: function(res) {
									uni.hideLoading()
									_this.imgUrl = res.tempFilePath
									_this.saveCanvasLoading = false
									_this.saveing = false
									callback()
								},
								fail: function(err) {
									console.log(err)
								}
							}, this);
						}, 100)
					})
				} else if (this.currentType === TOOL_TYPE.CROP) {
					const y = this.cropContainer.top
					const x = this.cropContainer.left
					const width = this.imgScaleW - (this.cropContainer.left + this.cropContainer.right)
					const height = this.imgScaleH - (this.cropContainer.top + this.cropContainer.bottom)

					this.saveCanvas.width = _this.imgScaleW
					this.saveCanvas.height = _this.imgScaleH
					this.saveCanvasLoading = true

					this.$nextTick(() => {
						const ctx = uni.createCanvasContext(saveCanvasId, this)
						uni.showLoading({
							title: loadMsg,
						});

						ctx.drawImage(_this.imgUrl, 0, 0, _this.imgScaleW, _this.imgScaleH);
						ctx.draw()

						setTimeout(() => {
							uni.canvasToTempFilePath({
								x,
								y,
								width,
								height,
								destWidth: width / _this.scale,
								destHeight: height / _this.scale,
								quality: 1,
								canvasId: SAVE_CANVAS_ID,
								success: function(res) {
									uni.hideLoading()
									_this.saveCanvasLoading = false
									_this.saveing = false
									_this.open(res.tempFilePath, false)
									callback()
								},
								fail: function(err) {

								}
							});
						}, 100)
					})
				} else if (this.currentType === TOOL_TYPE.ROTATE) {
					if (this.rotate === 90 || this.rotate === 270) {
						this.saveCanvas.width = _this.imgScaleH
						this.saveCanvas.height = _this.imgScaleW
					} else {
						this.saveCanvas.width = _this.imgScaleW
						this.saveCanvas.height = _this.imgScaleH
					}
					this.saveCanvasLoading = true

					this.$nextTick(() => {
						const ctx = uni.createCanvasContext(saveCanvasId, this)
						uni.showLoading({
							title: loadMsg,
						});

						if (_this.rotate) {
							ctx.rotate(_this.rotate * Math.PI / 180)
							// 绘制
							if (_this.rotate === 90) {
								ctx.drawImage(_this.imgUrl, 0, -_this.imgScaleH, _this.imgScaleW, _this.imgScaleH)
							} else if (_this.rotate === 180) {
								ctx.drawImage(_this.imgUrl, -_this.imgScaleW, -_this.imgScaleH, _this.imgScaleW,
									_this.imgScaleH)
							} else if (_this.rotate === 270) {
								ctx.drawImage(_this.imgUrl, -_this.imgScaleW, 0, _this.imgScaleW, _this.imgScaleH);
							}
						} else {
							ctx.drawImage(_this.imgUrl, 0, 0, _this.imgScaleW, _this.imgScaleH);
						}
						ctx.draw()
						setTimeout(() => {
							uni.canvasToTempFilePath({
								x: 0,
								y: 0,
								width: _this.saveCanvas.width,
								height: _this.saveCanvas.height,
								destWidth: _this.saveCanvas.width / _this.scale,
								destHeight: _this.saveCanvas.height / _this.scale,
								quality: 1,
								canvasId: SAVE_CANVAS_ID,
								success: function(res) {
									uni.hideLoading()
									_this.imgUrl = res.tempFilePath
									_this.saveCanvasLoading = false
									_this.saveing = false
									_this.open(res.tempFilePath, false)
									callback()
								},
								fail: function(err) {

								}
							});
						}, 100)
					})
				}
			},
			handleOK() {
				this.$emit('ok', this.imgUrl)
				uni.$emit(EVENT_CONSTANTS.GLOBAL_HIDE_TABBAR, true)
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './index.scss';
</style>